package com.pansoft.openplanet.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.google.android.material.appbar.AppBarLayout;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.core.xml.StubObject;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.service.Registry;
import com.efounder.util.AbFragmentManager;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.newasset.bean.MenuBean;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.adapter.AssetAllAppAdapter;
import com.pansoft.openplanet.adapter.AssetAllAppTopAdapter;
import com.pansoft.openplanet.bean.*;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;
import com.utilcode.util.*;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2019/4/22 10:13
 * @desc :  更多 全部应用
 * @version: 1.0
 */
public class AssetAllApplicationActivity extends BaseActivity implements View.OnClickListener {

    /**
     * 标题
     */
    private TextView tv_title;
    private QMUITabSegment tabLayout;
    /**
     * 功能列表
     */
    private RecyclerView recycler_view;
    /**
     * 功能集合
     */
    private List<AllAppTabItemBean> tabItemBeans = new ArrayList<>();
    /**
     * 功能列表的adapter
     */
    private AssetAllAppAdapter assetAllAppAdapter;
    private RelativeLayout rl_title;
    private AppBarLayout appbar;
    /**
     * 顶部的图标列表
     */
    private RecyclerView rv_top;
    /**
     * 顶部图标列表的adapter
     */
    private AssetAllAppTopAdapter topAdapter;
    /**
     * recyclerView是否滚动
     */
    private boolean isScroll = false;

    /**
     * 是否已经添加过空白布局
     */
    private boolean isAddEmptyLayout;
    private int firstPosition = -2;

    /**
     * tab 的菜单集合
     */
    private String[] tabMenus;
    private List<WalletBean> walleatBeanList = new ArrayList<>();
    private AccountDao accountDao;
    private String filePath = "";
    private String address = "";
    private List<MenuBean> menuBeans = new ArrayList<>();
    private List<StubObject> mainMenus;

    public static void start(Context context) {
        Intent starter = new Intent(context, AssetAllApplicationActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.assets_activity_all_application);
        EventBus.getDefault().register(this);
        tabMenus = new String[]{getString(R.string.open_planet_asset_all_app_comm),/*getString(R.string.open_planet_asset_all_app_other)*/};
        initView();
        initListener();
    }

    /**
     * 滚动点击事件处理
     */
    private void initListener() {
        //顶部列表点击事件
        topAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AssetEditApplicationActivity.start(AssetAllApplicationActivity.this);
            }
        });
        //功能菜单列表点击事件
        assetAllAppAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AllAppTabItemBean allAppTabItemBean = assetAllAppAdapter.getData().get(position);
                handleIntent(allAppTabItemBean.t);
            }
        });
        //recyclerView 菜单列表滑动监听
        recycler_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //平滑移动需要在此处判断处理没有到顶部的position
                if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == newState) {//
//                    firstPosition = 0;
//                    mShouldScroll = false;
//                    smoothMoveToPosition(recycler_view, mToPosition);
                } else if (RecyclerView.SCROLL_STATE_IDLE == newState) {
                    isScroll = false;

                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isScroll) {
                    return;
                }
                firstPosition = 0;
                LinearLayoutManager layoutManager = (LinearLayoutManager) recycler_view.getLayoutManager();
                //获取第一个显示的位置
                int position = layoutManager.findFirstVisibleItemPosition();
                //获取第一个位置item的View
                View firstVisiableChildView = layoutManager.findViewByPosition(position);
                //获取第一个位置item的高度，用于计算空白区域的高度
                int itemHeight = firstVisiableChildView.getHeight();
                //如果position大于等于列表集合的长度，return
                if (position >= tabItemBeans.size()) {
                    return;
                }
                AllAppTabItemBean allAppTabItemBean = tabItemBeans.get(position);
                //如果第一个item位置position为0，tabLayout指定为0，并添加空白布局
                if (position == 0) {
                    tabLayout.selectTab(0);
                    //判断是否已经添加，只添加一次
                    if (!isAddEmptyLayout) {
                        //添加recyclerView底部空白布局
                        addBottomEmptyLayout(itemHeight);
                        isAddEmptyLayout = true;
                    }
                }
                //header为null的时候return 不需要指定tab位置
                if (allAppTabItemBean.header == null) {
                    return;
                }
                /**
                 * 根据滚动的item 指定tab菜单的位置
                 */
                for (int i = 0; i < tabMenus.length; i++) {
                    if (allAppTabItemBean.header.equals(tabMenus[i])) {
                        tabLayout.selectTab(i);
                    }
                }
            }
        });

        /**
         * tab的点击事件 控制列表的位置
         */
        tabLayout.setOnTabClickListener(new QMUITabSegment.OnTabClickListener() {
            @Override
            public void onTabClick(int index) {
                appbar.setExpanded(false);
                if (index == 0) {
                    firstPosition = 0;
                    recycler_view.scrollToPosition(0);
                    return;
                }
                String title = tabLayout.getTab(index).getText().toString();
                for (int i = 0; i < tabItemBeans.size(); i++) {
                    AllAppTabItemBean tabItemBean = tabItemBeans.get(i);
                    if (tabItemBean.header != null && title.equals(tabItemBean.header)) {

                        moveToPosition(i);
                    }
                }

            }
        });
    }

    int heightSum;

    /**
     * 控制recyclerView底部的空白区域
     *
     * @param itemHeight
     */
    private void addBottomEmptyLayout(final int itemHeight) {
        //最后一栏的数量
        int i = 0;
        List<AllAppTabItemBean> appTabItemBeans = new ArrayList<>();
        appTabItemBeans.addAll(tabItemBeans);
        Collections.reverse(appTabItemBeans);
        //计算最后一栏的数量
        for (AllAppTabItemBean tabItemBean : appTabItemBeans) {
            if (tabItemBean.header != null) {
                break;
            }
            i++;

        }
        //最后一栏的行数
        int count = 0;
        if ((i % 4) > 0) {
            count = ((int) (i / 4)) + 1;
        } else if (i % 4 == 0) {
            count = i / 4;
        } else if (i % 4 < 0) {
            count = 1;
        }
        //移除底部布局
        assetAllAppAdapter.removeAllFooterView();
        //空白布局
        View view = LayoutInflater.from(AssetAllApplicationActivity.this).inflate(R.layout.asset_item_header_total_layout, recycler_view, false);
        FrameLayout frameLayout = view.findViewById(R.id.fl_view);
        GridLayoutManager.LayoutParams layoutParams = (GridLayoutManager.LayoutParams) frameLayout.getLayoutParams();
        //item的高度
        int itemHeightSum = ((count) * itemHeight);
        //item标题的高度
        int marginHeight = ConvertUtils.dp2px(40);
        layoutParams.height = recycler_view.getMeasuredHeight() - itemHeightSum - marginHeight;
        frameLayout.setLayoutParams(layoutParams);
        //仿支付宝添加空白布局
        assetAllAppAdapter.addFooterView(view);
    }

    //目标项是否在最后一个可见项之后
    private boolean mShouldScroll;
    //记录目标项位置
    private int mToPosition;


    /**
     * 非平滑移动   指定某个位置移动到顶部
     *
     * @param position
     */
    private void moveToPosition(int position) {
        if (position != -1) {
            recycler_view.scrollToPosition(position);
            LinearLayoutManager mLayoutManager =
                    (LinearLayoutManager) recycler_view.getLayoutManager();
            mLayoutManager.scrollToPositionWithOffset(position, 0);
        }
    }

    /**
     * 使指定的项平滑到顶部
     *
     * @param mRecyclerView
     * @param position      待指定的项
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        int firstItemPosition = -1;
        int lastItemPosition = -1;

        //todo 获取第一个和最后一个可见位置方式1
        // 第一个可见位置
        firstItemPosition = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        lastItemPosition = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));

        if (firstPosition == position) {
            return;
        }
        firstPosition = position;

        isScroll = true;
        //todo 获取第一个和最后一个可见位置方式2
        // 判断是当前layoutManager是否为LinearLayoutManager
        // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
//        RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
//        if (layoutManager instanceof LinearLayoutManager) {
//            LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
//            //获取第一个可见view的位置
//            firstItemPosition = linearManager.findFirstVisibleItemPosition();
//            //获取最后一个可见view的位置
//            lastItemPosition = linearManager.findLastVisibleItemPosition();
//
//        }

//        LogUtils.e( "smoothMoveToPosition: firstItemPosition::" + firstItemPosition + " lastItemPosition::" + lastItemPosition + "\n"+"position--->"+position);
//
        if (position < firstItemPosition) {
            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItemPosition) {
            // 第二种可能:跳转位置在第一个可见位置之后,在最后一个可见项之前
            int movePosition = position - firstItemPosition;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);//dx>0===>向左  dy>0====>向上
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }

    private void initView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.open_planet_asset_all_app));
        appbar = (AppBarLayout) findViewById(R.id.appbar);
        rl_title = (RelativeLayout) findViewById(R.id.title);
        tabLayout = (QMUITabSegment) findViewById(R.id.tabSegment);
        rv_top = (RecyclerView) findViewById(R.id.rv_top);
        appbar.setOnClickListener(this);

        rv_top.setLayoutManager(new GridLayoutManager(this, 6));
        topAdapter = new AssetAllAppTopAdapter(R.layout.asset_item_all_app_top_list, menuBeans);
        rv_top.setAdapter(topAdapter);
        recycler_view = (RecyclerView) findViewById(R.id.recycler_view);
        recycler_view.setLayoutManager(new GridLayoutManager(this, 4));
//        tabItemBeans = getSampleData();
        assetAllAppAdapter = new AssetAllAppAdapter(R.layout.assets_item_all_app_content_layout, R.layout.asset_item_all_app_header_layout, tabItemBeans, false);
        recycler_view.setAdapter(assetAllAppAdapter);
        iniTabLayout();
        //获取菜单列表
        getMenuList();
    }

    private void iniTabLayout() {
        tabLayout.reset();
        //添加菜单
        QMUITabBuilder tabBuilder = tabLayout.tabBuilder();
//        tabBuilder.setColorAttr(R.color.black_text_color, R.color.title_Background);
        for (String tab : tabMenus) {
            tabLayout.addTab(tabBuilder.setText(tab)
                    .build(this));
        }
        tabLayout.setMode(QMUITabSegment.MODE_SCROLLABLE);
//        tabLayout.setDefaultNormalColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
//        tabLayout.setDefaultSelectedColor(JfResourceUtil.getSkinColor(R.color.title_Background));

        tabLayout.setDefaultTextSize(ConvertUtils.dp2px(15), ConvertUtils.dp2px(15));
        tabLayout.notifyDataChanged();
    }

    /**
     * 读取菜单配置
     */
    private void getMenuList() {
        tabItemBeans.clear();
        menuBeans.clear();
//        tabItemBeans.add(new AllAppTabItemBean(false, "常用"));
        mainMenus = Registry.getRegEntryList("NewAssetRoot");
        //1、获取缓存的菜单数据
        boolean isCache = !SPUtils.getInstance(AssetEditApplicationActivity.ASSET_MENU).getString("NewAssetRoot", "").equals("");
        //2.如果有缓存从缓存中读取，否则从配置菜单中读取
        if (isCache) {
            loadCacheMenuData();
        }
        if (mainMenus != null) {
            for (int i = 0; i < mainMenus.size(); i++) {
                StubObject stubObject = mainMenus.get(i);
                MenuBean menuBean = new MenuBean(stubObject.getString("icon", ""),
                        stubObject.getCaption(),
                        stubObject.getString("AndroidShow", ""), stubObject.getString("multiLanguageKey", ""));
                menuBean.setStubObject(stubObject);
                tabItemBeans.add(new AllAppTabItemBean(menuBean));
                //跳出是因为最后一个是更多菜单按钮
                if (i > (mainMenus.size() - 3)) {
                    break;
                }
                //顶部只能显示5个图标  加一个更多图标
                if (i > 4) {
                    continue;
                }
                //没有缓存添加配置文件中数据
                if (!isCache) {
                    menuBeans.add(menuBean);
                }

            }
            //顶部菜单添加更多图标
            StubObject stubObject = mainMenus.get(mainMenus.size() - 1);
            menuBeans.add(new MenuBean(stubObject.getString("icon", ""),
                    stubObject.getCaption(),
                    stubObject.getString("AndroidShow", "")));
//            tabItemBeans.add(new AllAppTabItemBean(true, getString(R.string.open_planet_asset_all_app_other)));
//            tabItemBeans.add(new AllAppTabItemBean(new MenuBean(menuBeans.get(0).getIcon(),menuBeans.get(0).getName(),menuBeans.get(1).getClassName())));
        }

        topAdapter.notifyDataSetChanged();
        assetAllAppAdapter.notifyDataSetChanged();
    }

    /**
     * 加载缓存中的数据
     */
    private void loadCacheMenuData() {
        //2.1 读取缓存数据
        String cacheMenu = SPUtils.getInstance(AssetEditApplicationActivity.ASSET_MENU).getString("NewAssetRoot", "");
        //2.2解析缓存菜单集合
        List<MenuBean> cacheMenuBeas = JSONArray.parseArray(cacheMenu, MenuBean.class);
        //2.3 加载数据到顶部列表中
        for (int i = 0; i < cacheMenuBeas.size(); i++) {
            //顶部只能显示5个图标  加一个更多图标
            if (i > 4) {
                break;
            }
            menuBeans.add(cacheMenuBeas.get(i));
        }
    }

    @Override
    public void onClick(View v) {
        //点击顶部的布局 跳转编辑应用界面
        if (v.getId() == R.id.appbar) {
            AssetEditApplicationActivity.start(this);
        }
    }

    /**
     * 功能列表点击事件处理
     *
     * @param menuBean
     */
    private void handleIntent(MenuBean menuBean) {
        if (menuBean == null) {
            return;
        }
        String androidShow = menuBean.getClassName();
        try {
            //交易
            if ("tx".equals(androidShow)) {
                TradeLineActivity.startTradeLineActivity
                        (this, IPAssetsConstant.CHAIN_ID_TURBOCHAIN, ResStringUtil.getString(R.string.open_planet_transfer_list), walleatBeanList.get(0).getAddress(),
                                "", walleatBeanList.get(0).getBalance(), null,
                                walleatBeanList.get(0).getFilePath(), 0);
                //未开通
            } else if ("todo".equals(androidShow)) {
                new AlertDialog.Builder(this).setTitle(ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_one_click_coin))
                        .setMessage(ResStringUtil.getString(R.string.open_planet_recharge_no_dredge))
                        .setCancelable(true)
                        .setPositiveButton(R.string.common_text_confirm, null).show();
                //安全加固
            } else if ("safe".equals(androidShow)) {
                Intent intent = new Intent(this, SafetyArchitectureActivity.class);
                intent.putExtra("filePath", filePath);
                startActivity(intent);
                //红包
            } else if ("com.pansoft.openplanet.activity.LuckMoneyPrepareActivity".equals(androidShow)) {
                LuckMoneyPrepareActivity.start(this);
                //没配置页面
            } else if (TextUtils.isEmpty(androidShow)) {
                return;
                //其他
            } else {
                AbFragmentManager abFragmentManager = new AbFragmentManager(this);
                abFragmentManager.startActivity(menuBean.getStubObject(), 0, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取本地钱包地址
     */
    private List<WalletBean> getWallet() {

        Account mainAccount = new AccountDao(this).getMainAccount();
        if (mainAccount == null) {
            mainAccount = accountDao.getAccount(EnvironmentVariable.getProperty("tc_ethAddress"));
            if (mainAccount != null) {
                mainAccount.setMaster(true);
                mainAccount.setEnable(true);
                mainAccount.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                accountDao.insertOrReplace(mainAccount);
            } else {
                return walleatBeanList;
            }
        }

        WalletBean walletBean = new WalletBean();
        walletBean.setAddress(mainAccount.getAddress());
        walletBean.setFile(new File(mainAccount.getFileName()));
        walletBean.setFilePath(mainAccount.getFileName());
        walletBean.setAccountName(mainAccount.getAcccountName());
        walletBean.setAvatar(mainAccount.getAccountAvatar());
        walleatBeanList.add(walletBean);
        address = walleatBeanList.get(0).getAddress();
        filePath = walleatBeanList.get(0).getFilePath();
        return walleatBeanList;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshTopMenu(EventMenuBean eventMenuBean) {
        if (eventMenuBean != null && eventMenuBean.type == 0) {
            //1、顶部加载缓存中的数据
            getMenuList();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
